
function TwifySlider( element ) {

	this.options = {
		outpos	: 200,
		inpos	: 0,
	};

	this.el = $(element);
	this.currentSlide = 0;

	this.init();
}

TwifySlider.prototype.init = function (){

	this.nextbutton = this.el.find('.next');
	this.prevbutton = this.el.find('.prev');
	this.container = this.el.find('.container');
	this.slides = this.container.children();

	// If has more than 1 child, make animatable
	if(this.slides.length > 1){

		// Show first slide
		this.currentSlide = parseInt($.cookie("twifyslider-current")) || 0;

		// Show the first
		this._animateIn( this.currentSlide, true );

		// Attach event listeners
		this._attachEventlisteners();
	}

	var that = this;
	this.interval = setInterval( function(){
		that._show('next');
	}, 3000);
}

TwifySlider.prototype._show = function( dir ){

	// Find out where we're going
	if(dir === "next"){
		if( this.currentSlide + 1 >= this.slides.length ){
			this.currentSlide = 0;
		}
		else {
			this.currentSlide++;
		}
	}
	else if(dir === "prev") {
		if( this.currentSlide -1 < 0 ){
			this.currentSlide = this.slides.length -1 ;
		}
		else {
			this.currentSlide--;
		}
	}
	
	// Animate it
	this._animateIn( this.currentSlide );
}

TwifySlider.prototype._animateIn = function( ix, motionless ){
	
	var duration = motionless ? 0 : 150;
	// Animate
	for(var i = 0; i < this.slides.length; i++){

		// Are we on this RIGHT item?
		if( i === ix ){
			$(this.slides[i])
				.stop()
				.animate({ left : this.options.inpos, opacity : 1 }, duration);

		// No, is some unwanted stuff still in view? TAKE'M OUT!! 
		} else if( parseInt( $(this.slides[i]).css("left")) <= this.options.outpos ){
			// Move'm outta view
			$(this.slides[i])
				.stop()
				.animate({ left : this.options.outpos, opacity : 0 }, duration);
		}
	}

	// Set cookie tracker 
	$.cookie("twifyslider-current", this.currentSlide);
}

TwifySlider.prototype._attachEventlisteners = function(){
	
	var pb = this.prevbutton,
		nb = this.nextbutton;

	pb.on("click", this, function( e ){ e.data._show( "prev" )});
	nb.on("click", this, function( e ){ e.data._show( "next" )});
}
